<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { RewriteButton } from '../custom-editor-menus/RewriteButton'
import { AmplificationButton } from '../custom-editor-menus/AmplificationButton'
import { ShorthandButton } from '../custom-editor-menus/ShorthandButton'
import { ContinuedButton } from '../custom-editor-menus/ContinuedButton'
import { ExportsButton } from '../custom-editor-menus/ExportsButton'
import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { Boot } from '@wangeditor/editor'

// 接收传递过来的数据
const props = defineProps<{
  vHtml: string
}>()

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 内容 HTML
const valueHtml = ref(props.vHtml)
defineExpose({ valueHtml })
// 模拟 ajax 异步获取内容
onMounted(() => {
  setTimeout(() => {}, 1500)
})

const editorConfig = { placeholder: '在左侧指令区输入相关信息' }
const myRegistrationMenu = () => {
  Boot.registerMenu({
    key: 'rewrite',
    factory: () => new RewriteButton()
  })

  Boot.registerMenu({
    key: 'amplification',
    factory: () => new AmplificationButton()
  })

  Boot.registerMenu({
    key: 'shorthand',
    factory: () => new ShorthandButton()
  })

  Boot.registerMenu({
    key: 'continued',
    factory: () => new ContinuedButton()
  })

  Boot.registerMenu({
    key: 'exports',
    factory: () => new ExportsButton()
  })
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
  if (!editor.getAllMenuKeys()?.includes('rewrite')) {
    //判断如果已经插入进去，不在二次插入
    myRegistrationMenu()
  }
}
const toolbarConfig = {
  toolbarKeys: [
    'bold',
    'italic',
    'underline',
    'through',
    '|',
    'amplification',
    'rewrite',
    'shorthand',
    'continued',
    '|',
    'redo',
    'undo',
    '|',
    'exports'
  ]
}
</script>

<template>
  <div style="border: 1px solid #ccc" class="h-full flex relative flex-col overflow-hidden">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      class="w-full"
      :defaultConfig="toolbarConfig"
      mode="default"
    />
    <Editor
      style="overflow-y: hidden"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      class="flex-grow"
      mode="default"
      @on-created="handleCreated"
    />
    <div
      class="absolute bottom-4 left-1/2 py-1 px-4 border-1 border-solid border-indigo-600 text-indigo-600 rounded-3xl"
    >
      续写
    </div>
  </div>
</template>
